﻿using System.Configuration;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Context;
using NHibernate.Tool.hbm2ddl;
using Salary.NHibernate.Mappings;

namespace Salary.NHibernate
{
    public class NhConfigurator
    {
        private static ISessionFactory _sessionFactory;

        public ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                {
                    InitializeSessionFactory();
                }

                return _sessionFactory;
            }
        }
        
        public static ISessionFactory InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2012
                .ConnectionString(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
                .Mappings(m =>
                            m.FluentMappings
                                .AddFromAssemblyOf<EmployeeMap>())
                .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(false, true))
                .CurrentSessionContext<ThreadStaticSessionContext>()
                .BuildSessionFactory();
            return _sessionFactory;
        }
        
        public static ISessionFactory RecreateDb()
        {
            _sessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2012
               .ConnectionString(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString))
               .Mappings(m =>
                            m.FluentMappings
                                .AddFromAssemblyOf<EmployeeMap>())
                .CurrentSessionContext<ThreadStaticSessionContext>()
                .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(false, true))
                .BuildSessionFactory();
            return _sessionFactory;
        }

        public static ISession OpenSession()
        {
            return _sessionFactory.OpenSession();
        }
    }
}